<template>
    <div class="frameworkOut">
        <!--   文书查看界面   -->
        <div class="frameworkIn1" v-if="clickTemplate">
            <div class="templateHeader">
                <span style="padding-bottom: 4px;">文书{{ templateData.isEdit }}->{{ templateData.documentName }}</span>
                <span style="float: right;padding-bottom: 6px;">
                    <el-button type="danger" icon="Close" size="small" @click="closeTemplate()">
                    </el-button>
                </span>
            </div>
            <iframe style="width:100%;height:calc(100% - 76px);border:none;" ref="iframe"
                :src="'./' + templateData.templateNo"></iframe>
            <div class="templateFooter">
                <el-button v-if="templateData.isEdit == '编辑'" @click="$refs.iframe.contentWindow.postForm();">提交
                </el-button>
                <el-button v-if="templateData.isEdit == '查看'" @click="closeTemplate();">确定
                </el-button>
            </div>
        </div>
        <!--   案件管理界面   -->
        <div class="frameworkIn2" v-show="!clickTemplate">
            <!--      上半部分表格-->
            <div class="top-class-table" style="height:calc(50% - 40px)">
                <!--   案件卷宗内容   -->
                <div class="header">
                    <span>{{ caseLog.menu }} -> {{ caseLog.title }}</span>
                </div>
                <div class="button_group">

                    <el-input v-model="casePage.search" style="width: 300px;" placeholder="输入案件名称搜索">
                    </el-input>
                    <el-button type="primary" icon="Search" @click="getCaseTableData">搜索</el-button>

                    <el-button-group style="float: right">
                        <!--            新建案件-->
                        <el-button v-if="caseLog.id == '0' && permissionIsShow.caseAdd" type="primary"
                            icon="DocumentAdd" @click="clickAddCase">新建案件
                        </el-button>
                        <!--            相关附件-->
                        <el-button type="primary" icon="Document" @click="clickRelatedAnnex">相关附件
                        </el-button>
                        <el-button type="primary" icon="CircleCheck"
                            v-if="permissionIsShow.casePass && (caseLog.id == '0' || caseLog.id == '1' || caseLog.id == '3' || caseLog.id == '5' || caseLog.id == '7')"
                            @click="clickSubmitReview()">{{ caseLog.id == '0' ? '提交审核' : '审核通过' }}
                        </el-button>
                        <!--<el-button type="primary" icon="CircleCheck" @click="clickTransferCase()">移交案件-->
                        <!--</el-button>-->
                        <el-button v-if="permissionIsShow.casePass && caseLog.id == '9'" type="primary"
                            icon="CircleCheck" @click="caseClickApprovePass()">审批通过
                        </el-button>
                        <el-button
                            v-if="permissionIsShow.caseReject && (caseLog.id == '1' || caseLog.id == '3' || caseLog.id == '5' || caseLog.id == '7' || caseLog.id == '9')"
                            type="primary" icon="CircleClose" @click="clickReject()">驳回
                        </el-button>
                    </el-button-group>
                </div>
                <el-table :data="caseTableData" ref="table1" @row-click="(row) => selectCaseRow(row)"
                    highlight-current-row :header-cell-style="{ background: '#f4f3f9' }"
                    style="width:100%;height:calc(50vh - 156px)" border>
                    <el-table-column prop="unitName" label="所属部门"></el-table-column>
                    <el-table-column prop="caseNo" label="案件编号">
                        <template v-slot="scope">
                                {{ `朔开（${scope.row.documentNumber}）检字[${scope.row.enterTime ? new
                                    Date(scope.row.enterTime).getFullYear() : ''}]第${scope.row.caseNo}号`}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="caseName" label="案件名称"></el-table-column>
                    <el-table-column prop="process" label="案件状态">
                        <template v-slot="scope">
                            <span v-if="convertProcess(scope.row.process).flag">
                                {{ convertProcess(scope.row.process).label }}
                            </span>
                            <el-popover v-else effect="light" trigger="hover" placement="top" width="auto">
                                <template #default>
                                    <div>驳回说明: {{ scope.row.backReason }}</div>
                                </template>
                                <template #reference>
                                    <el-link :underline="false" type="danger">
                                        {{ convertProcess(scope.row.process).label }}
                                    </el-link>
                                </template>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column prop="routineType" label="案件程序"></el-table-column>
                    <el-table-column prop="enterTime" label="录入时间"></el-table-column>
                    <!--          操作-->
                    <el-table-column v-if="caseLog.id == '0'" fixed="right" align="center" prop="operate" label="操作"
                        width="250px">
                        <template v-slot="scope">
                            <el-button type="primary" icon="Edit" size="small" v-if="permissionIsShow.caseEdit"
                                @click="clickEditCase(scope.row)">编辑</el-button>
                            <el-button type="success" icon="Search" size="small"
                                @click="clickViewCase(scope.row)">查看</el-button>
                            <el-button v-if="permissionIsShow.caseDelete && scope.row.isHanding === '0'" type="danger"
                                icon="Delete" size="small" @click="clickDeleteCase(scope.row.id)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column v-else fixed="right" align="center" prop="operate" label="操作" width="230px">
                        <template v-slot="scope">
                            <el-button type="success" icon="Search" size="small"
                                @click="clickViewCase(scope.row)">查看</el-button>
                            <el-button v-if="caseLog.id == '11'" type="primary" icon="Download" size="small"
                                @click="clickBatchDownload(scope.row)">下载本案文书
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="footer">
                <el-pagination @size-change="handleCaseSizeChange" @current-change="handleCaseCurrentChange"
                    :page-sizes="[5, 10, 20]" :page-size="casePage.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="casePage.total">
                </el-pagination>
            </div>
            <!--       下半部分表格-->
            <div class="bottom-class-table" style="height:calc(50% - 40px)">
                <!--   案件文书内容   -->
                <div class="header">
                    <span>案件文书</span>
                </div>
                <div class="button_group" v-if="caseLog.id == '0' && permissionIsShow.documentAdd">
                    <el-select v-model="templateData.addTemplateNo" placeholder="请选择要增加的文书名称"
                        style="margin-right: 10px;width: 300px;" clearable @change="selectAddArchive">
                        <el-option v-for="x in NowDocument" :key="x.key" :value="x.key" :label='x.name'>
                        </el-option>
                    </el-select>

                    <el-button type="primary" @click="clickNextDocumentType()">下一步
                    </el-button>
                    <el-button type="primary" @click="clickLastDocumentType()">上一步
                    </el-button>
                    <el-button style="margin-left: 10px" type="primary" icon="DocumentAdd" @click="this.templateData.isEdit = '编辑';
                    clickAddDocument(null, false)">增加
                    </el-button>
                </div>
                <el-table :data="templateTableData" :header-cell-style="{ background: '#f4f3f9' }"
                    :style="{ height: (caseLog.id == '0' && permissionIsShow.documentAdd ? 'calc(50vh - 156px)' : 'calc(50vh - 116px)') }"
                    border @row-dblclick="DoubleHandleDocumentsRowClick">
                    <el-table-column prop="documentName" label="文书名称">
                    </el-table-column>
                    <el-table-column align="center" prop="uploadTime" label="上报时间" width="300">
                    </el-table-column>
                    <el-table-column align="center" prop="status" label="状态" width="200">
                        <template v-slot="scope">
                            <span v-for="x in templateTableStatus">
                                {{ scope.row.status == x.key ? x.label : "" }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="管理" width="260">
                        <template v-slot="scope">
                            <el-button v-if="permissionIsShow.documentEdit && scope.row.status != '4'" type="primary"
                                icon="Edit" size="small" @click="editAndViewDocuments('编辑', scope.row)">编辑
                            </el-button>
                            <el-button type="success" icon="Search" size="small"
                                @click="editAndViewDocuments('查看', scope.row)">查看
                            </el-button>
                            <el-button
                                v-if="permissionIsShow.documentDelete && caseLog.id == '0' && scope.row.status != '4'"
                                type="danger" icon="Delete" size="small" @click="clickDeleteTemplate(scope.row.id)">删除
                            </el-button>
                            <div
                                v-if="permissionIsShow.documentPass && (caseLog.id == '0' || caseLog.id == '1' || caseLog.id == '3' || caseLog.id == '5' || caseLog.id == '7' || caseLog.id == '9')">
                                <el-button v-if="caseLog.templateStatus.includes(scope.row.status)" type="primary"
                                    icon="CircleCheck" size="small" @click="clickApprovedTemplate(scope.row.id)">通过
                                </el-button>
                            </div>
                            <el-button v-if="caseLog.id == '11'" type="primary" icon="Download" size="small"
                                @click="clickDownloadTemplate(scope.row, this.row.caseNo)">
                                下载文书
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="footer">
                <el-pagination @size-change="handleTemplateSizeChange" @current-change="handleTemplateCurrentChange"
                    :page-sizes="[5, 10, 20]" :page-size="templateTablePage.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="templateTablePage.total">
                </el-pagination>
            </div>
        </div>
        <!--   新建或编辑案件弹窗   -->
        <el-dialog v-model="changeCase" :close-on-click-modal="false" @close="quxiao()" :title="caseTitleType + '案件'"
            width="850px" close-on-press-escape align-center draggable>
            <el-form label-width="100px" label-position="right" :model="caseForm" :rules="caseRules" ref="caseForm">
                <el-form-item label="所属部门" prop="unitId"
                    v-if="caseTitleType == '新增' && (loginUserInfo.responsibleScope == '5' || loginUserInfo.responsibleScope == '4')">
                    <el-select v-model="caseForm.unitId" placeholder="请选择所属部门" style="width: 100%" clearable>
                        <el-option v-for="x in addSelectData.unitData" :key="x.id" :value="x.id" :label="x.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="编号" prop="caseNo">
                    <el-input v-model="caseForm.caseNo" placeholder="请输入编号" />
                </el-form-item>
                <el-form-item label="案件名称" prop="caseName">
                    <el-input v-model="caseForm.caseName" placeholder="请输入案件名称" />
                </el-form-item>
                <el-form-item label="信息来源" prop="informSourceId">
                    <el-select v-model="caseForm.informSourceId" placeholder="请选择信息来源" style="width: 100%" clearable>
                        <el-option v-for="x in addSelectData.informSourceData" :key="x.id" :value="x.id"
                            :label="x.informName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="案件分类" prop="caseTypeId">
                    <el-select v-model="caseForm.caseTypeId" placeholder="请选择案件分类" style="width: 100%" clearable>
                        <el-option v-for="x in addSelectData.caseTypeData" :key="x.id" :value="x.id"
                            :label="x.typeName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="违法类型">
                    <el-input v-model="caseForm.illegalType" />
                </el-form-item>
                <el-form-item label="承办人一" prop="undertakerOne">
                    <el-select v-model="caseForm.undertakerOne" placeholder="请选择承办人一" style="width: 100%" clearable>
                        <el-option v-for="x in addSelectData.userData" :key="x.id" :value="x.id"
                                   :label="x.username" />
                    </el-select>
                </el-form-item>
                <el-form-item label="承办人二" prop="undertakerTwo">
                    <el-select v-model="caseForm.undertakerTwo" placeholder="请选择承办人二" style="width: 100%" clearable>
                        <el-option v-for="x in addSelectData.userData" :key="x.id" :value="x.id"
                                   :label="x.username" />
                    </el-select>
                </el-form-item>
                <el-form-item label="案件说明">
                    <el-input type="textarea" v-model="caseForm.explains" :autosize="{ minRows: 1, maxRows: 4 }"
                        style="width:100%" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="caseForm.remark" type="textarea" :autosize="{ minRows: 1, maxRows: 4 }"
                        style="width:100%" />
                </el-form-item>
                <el-form-item v-if="caseTitleType == '新增'" label="附件">
                    <el-upload :action="'api/related-file/uploadSign'" :file-list="caseForm.annex"
                        :before-upload="beforeAnnexUpload" :on-success="annexUploadSuccess" :on-remove="annexRemove"
                        style="width:100%" drag multiple>
                        <el-icon class="el-icon--upload">
                            <upload-filled />
                        </el-icon>
                        <div class="el-upload__text">
                            拖拽或<em>点击</em>上传
                        </div>
                        <div class="el-upload__tip">
                            (请上传小于100MB的文件)
                        </div>
                    </el-upload>
                </el-form-item>
                <!--     按钮     -->
                <div style="display: flex;justify-content: flex-end">
                    <el-button type="primary" @click.native="clickChangeCaseSure('caseForm')">确定
                    </el-button>
                    <el-button @click.native="quxiao()">取消
                    </el-button>
                </div>
            </el-form>
        </el-dialog>

        <!--   相关附件弹窗   -->
        <el-dialog v-model="relatedAnnex" :close-on-click-modal="false" title="相关附件" width="1000px" align-center
            draggable @close="relatedAnnexClose">
            <div style="display: flex;margin-bottom: 10px">
                <el-button type="primary" style="margin-right: 15px  " @click="addRelatedAnnex">上传</el-button>
                <el-input v-model="searchFileName" placeholder="请输入附件名称"
                          style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px;" clearable />
                <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;"
                           @click="clickRelatedAnnex">查询</el-button>
            </div>
            <div class="annexDialog">
                <div class="header">
                    <span>附件查看->{{ row.caseName }}</span>
                </div>
                <el-table :data="annexTable" :cell-style="cellStyle" highlight-current-row
                    :header-cell-style="{ background: '#f4f3f9' }" class="annexTable"
                    style="width:100%;height:calc(100% - 29px)" border>
                    <el-table-column align="center" prop="fileName" label="附件名称" width="auto">
                    </el-table-column>
                    <el-table-column align="center" label="查看" width="250">
                        <template v-slot="scope">
                            <div>
                                <el-button icon="Edit" size="small" type="primary" @click="editRelatedAnnex(scope.row)">编辑</el-button>
                                <el-button icon="View" size="small" type="success" @click="openFile(scope.row.filePath)">查看</el-button>
                            </div>
                            <div>
                                <el-button icon="Download" size="small" type="warning"
                                           @click="downloadrelatedAnnexFile(scope.row)">下载</el-button>
                                <el-button icon="Delete" size="small" type="danger" @click="deleteRelatedAnnexFile(scope.row)">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>

        <!--   新增编辑附件弹窗   -->
        <el-dialog v-model="dialogRelatedAnnex" :close-on-click-modal="false" @close="closeRelatedAnnex"
                   :title="附件操作" width="550px" align-center draggable>
            <el-form label-width="100px" label-position="right" :model="annexForm">
                <el-form-item label="附件名称" prop="fileName">
                    <el-input placeholder="请输入附件名称" v-model="annexForm.fileName" autocomplete="off" clearable></el-input>
                </el-form-item>
                <el-form-item label="上传文件" prop="filePath">
                    <el-upload :action="'api/related-file/uploadSign'"
                               :before-upload="beforeAnnexUpload" :on-success="relatedAnnexUploadSuccess" :show-file-list="false">
                        <el-button size="center" type="primary">上传</el-button>
                        <el-button size="small" type="danger" v-if="annexForm.filePath" @click="deleteRelatedAnnex">删除</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div style="display: flex;justify-content: flex-end">
                <el-button type="primary" @click="submitRelatedAnnex()">确定</el-button>
                <el-button @click="closeRelatedAnnex()">取消
                </el-button>
            </div>
        </el-dialog>

        <!--   查看附件弹窗   -->
        <el-dialog title="文件预览" v-model="openItemFileDialog" width="70%" top="5vh" class="custom-preview-dialog"
                   @close="this.openItemFileDialog = false">
            <div class="preview-container" v-if="openItemFileDialog">
                <iframe :src="pdfSrc" frameborder="0"
                        style="background-color: #fff;width: 100%; height: 600px"></iframe>
            </div>
        </el-dialog>

        <!--   提交审查或提交审查弹窗   -->
        <el-dialog v-model="submit" :close-on-click-modal="false" @close="this.$refs.submitForm.resetFields()"
            :title="'提交' + '->' + row.caseName" width="850px" align-center draggable>
            <el-form label-width="100px" label-position="right" :model="submitForm" :rules="submitRules"
                ref="submitForm">
                <el-form-item v-if="isShowSubmitDepartmentSelect" label="科室" prop="departmentPath">
                    <el-cascader v-model="submitForm.departmentPath" :options="submitSelectOptions.departmentOption"
                        :props="cascaderProps" placeholder="请选择科室" @change="submitFormHandleDepartmentChange"
                        style="width: 100%;" />
                    <el-input v-model="submitForm.departmentId" type="hidden" />
                </el-form-item>
                <el-form-item v-if="isShowSubmitUserSelect" label="提交至" prop="userId">
                    <el-select v-model="submitForm.userId" placeholder="请选择用户" style="width:100%" clearable>
                        <el-option v-for="x in submitSelectOptions.userOption" :key="x.id" :value="x.id"
                            :label="`${x.username}（${x.roleName}）`" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="explain">
                    <el-input type="textarea" v-model="submitForm.explain" :autosize="{ minRows: 2, maxRows: 5 }"
                        style="width:100%" />
                </el-form-item>
            </el-form>
            <div style="display: flex;justify-content: flex-end">
                <el-button type="primary" @click="clickSubmitReviewSure()">确定</el-button>
                <el-button @click="clickCancelSubmitReview()">取消
                </el-button>
            </div>
        </el-dialog>

        <!-- 多提交方向弹窗 -->
        <el-dialog v-model="submitMultiDirectional" :close-on-click-modal="false" title="请选择提交对象" width="500px"
            align-center draggable>
            <el-table :data="multiDirectional" @row-click="handleMultiDirectionalRowClick" :show-header="false"
                style="width:100%" border>
                <el-table-column align="center" prop="label" label="提交方向">
                </el-table-column>
            </el-table>
        </el-dialog>

        <!--   查看案件弹窗   -->
        <el-dialog v-model="viewCase" :close-on-click-modal="false" :title="'查看案件信息->' + row.caseName" width="850px"
            close-on-press-escape align-center draggable>
            <el-table :data="viewCaseTable" :show-header="false" style="width:100%" border>
                <el-table-column align="center" prop="title" width="230"></el-table-column>
                <el-table-column prop="data"></el-table-column>
            </el-table>
        </el-dialog>

        <!--   驳回案件弹窗    -->
        <el-dialog v-model="back" :close-on-click-modal="false" :title="'驳回案件->' + row.caseName" width="850px"
            align-center draggable @close="this.$refs.backForm.resetFields()">
            <el-form label-width="100px" label-position="right" :model="backForm" :rules="backRules" ref="backForm">
                <el-form-item label="驳回说明" prop="backReason">
                    <el-input type="textarea" v-model="backForm.backReason" :autosize="{ minRows: 1, maxRows: 4 }"
                        style="width:100%" placeholder="请输入驳回说明" />
                </el-form-item>
            </el-form>
            <div style="display: flex;justify-content: flex-end">
                <!--        驳回确定按钮-->
                <el-button type="primary" @click="clickBackSure()">确定
                </el-button>
                <!--        驳回取消按钮-->
                <el-button @click="clickCancelBack()">取消
                </el-button>
            </div>
        </el-dialog>

        <el-dialog v-model="dialogNextDocumentType" :show-header=false title="下一步" width="30%">
            <el-table :data="nextDocumentTypeData" stripe border style="width: 100%;">
                <el-table-column align="center" label="分支" width="auto" property="selectDescription" />
                <el-table-column align="center" label="操作" width="150px">
                    <template v-slot="slotProps">
                        <el-button @click="clickNextDocumentTypeEnsure(slotProps.row)" type="primary">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="display: flex;justify-content: flex-end">
            </div>
        </el-dialog>
        <div v-if="isDownloading" class="download-mask" @click.stop></div>
        <div v-if="isDownloading" class="download-progress-container">
            <div style="display: flex; justify-content: flex-end;">
                <button class="download-close-btn" @click="isDownloading = false">
                    <el-icon>
                        <Close />
                    </el-icon>
                </button>
            </div>
            <el-progress type="dashboard" :percentage="percentage" :color="colors" :width="200"></el-progress>
            <p v-if="percentage !== 100">正在下载中</p>
            <p v-else>下载完成</p>
        </div>
    </div>
</template>

<script>
import request from "@/utils/request";
import axios from "axios";
import { serverIp } from "@/ipConfig/config"
import Steps from "./Steps.vue";

export default {
    name: "CaseManage",
    components: {
        Steps
    },

    data() {
        return {
            serverIp: serverIp, //附件上传路径
            addSelectData: {
                unitData: [], // 部门选项
                informSourceData: [], // 信息来源选项
                caseTypeData: [], // 案件分类
                userData: [], //承办人选项
            },
            //表单验证规则
            caseRules: {
                unitId: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
                caseNo: [
                    { required: true, message: '请输入编号', trigger: 'blur' },
                    { pattern: /^\d{5}$/, message: '编号必须为五位数字', trigger: 'blur' },
                ],
                caseName: [{ required: true, message: '请输入案件名称', trigger: 'blur' }],
                informSourceId: [{ required: true, message: '请选择信息来源', trigger: 'change' }],
                caseTypeId: [{ required: true, message: '请选择案件分类', trigger: 'change' }],
                undertakerOne: [{ required: true, message: '请选择承办人一', trigger: 'change' }],
                undertakerTwo: [{ required: true, message: '请选择承办人二', trigger: 'change' }],
            }, //新建案件

            // 案件表单数据
            caseForm: {
                transactor: '', // 录入人
                annex: [],
            },

            caseTableData: [], //案件表格
            casePage: {
                search: "", //搜索框数据
                currentPage: 1, //页码
                pageSize: 5, //页长
                total: 0,  //总表长
            },

            // 当前案件可添加文书
            NowDocument: [],

            templateTableData: [], //案件文书表格数据
            templateTablePage: {
                currentPage: 1,
                pageSize: 10,
                total: 0,
            },
            caseLog: JSON.parse(sessionStorage.getItem("caseLog") || "{}"),


            //当前选中行数据
            row: {},
            //保存当前选中行的索引
            selectedRowIndex: -1,
            selectedCaseNo: '',


            //查看文书数据
            templateData: {
                documentName: "", // 文书名称
                pstageId: "",
                documentType: "",
                templateNo: "", // 文书模板编号
                addTemplateNo: "", // 新增时选择的文书
                addDocumentName: "", // 新增时选择的文书名称
            },

            nextDocumentTypeData: [],//下一步
            dialogNextDocumentType: false,//下一步弹窗


            // 下载相关数据
            percentage: 0, // 进度条百分比
            isDownloading: false, // 下载状态标识
            totalFiles: 0, // 总文件数
            downloadedFiles: 0, // 已下载文件数
            colors: [
                { color: '#f56c6c', percentage: 20 },
                { color: '#e6a23c', percentage: 40 },
                { color: '#5cb87a', percentage: 60 },
                { color: '#1989fa', percentage: 80 },
                { color: '#6f7ad3', percentage: 100 }
            ],


            clickTemplate: false, //文书渲染
            relatedAnnex: false, //相关附件
            changeCase: false, //新建或编辑案件
            caseTitleType: '', //新建或编辑案件弹窗标题
            submit: false, //提交审查弹窗
            submitMultiDirectional: false, //多提交方向
            multiDirectional: [], //多提交方向

            dialogRelatedAnnex: false, //新建或编辑附件弹窗
            openItemFileDialog: false, //查看附件弹窗
            searchFileName: '', //附件模糊搜索
            annexTable: [], //相关附件列表
            annexForm: {}, //新建或编辑附件表单
            pdfSrc: '', //查看附件路径
            fileExt: '',

            viewCaseTable: [], //查看案件

            // 提交审核表单数据
            submitForm: {
                departmentId: '', //提交给谁的科室ID
                departmentPath: [], //提交给谁的科室路径
                userId: '', //提交给谁的用户ID
                explain: '', // 备注说明
            },
            // 提交审核科室表单级联选择器属性
            cascaderProps: {
                value: 'id',       // 选项值字段
                label: 'name',     // 选项显示名称字段
                children: 'children', // 子节点字段
                expandTrigger: 'hover', // 展开方式
                checkStrictly: true, // 级联选择器是否可以选择父科室
            },
            submitIndex: 0, //提交审核索引(用来控制向多种角色提交的情况)
            isShowSubmitDepartmentSelect: false, // 是否显示部门选择器
            isShowSubmitUserSelect: false, // 是否显示用户选择器

            // 提交审核表单下拉框选项
            submitSelectOptions: {
                departmentOption: [], //提交审核科室表单下拉框选项
                userOption: [], //提交审核用户表单下拉框选项
            },
            // 提交审核表单校验规则
            submitRules: {
                departmentPath: [{ required: true, message: '请选择科室', trigger: 'change' }],
                userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
            },

            // 驳回案件数据
            back: false, //驳回弹窗
            backForm: {
                id: '', // 案件ID
                backReason: '', // 驳回说明
            },
            backRules: {
                backReason: [{ required: true, message: '请输入驳回说明', trigger: 'blur' }],
            }, //驳回校验规则

            //映射表
            caseTableStatus: [
                { key: '0', label: '待提交', flag: true },
                { key: '1', label: '科室待审核', flag: true },
                { key: '2', label: '科室审核未通过', flag: false },
                { key: '3', label: '法律待审核', flag: true },
                { key: '4', label: '法律审核未通过', flag: false },
                { key: '5', label: '部门待审核', flag: true },
                { key: '6', label: '部门审核未通过', flag: false },
                { key: '7', label: '法律待审核', flag: true },
                { key: '8', label: '法律审核未通过', flag: false },
                { key: '9', label: '领导待审批', flag: true },
                { key: '10', label: '领导审批未通过', flag: false },
                { key: '11', label: '已归档', flag: true },
            ], //案件表格状态

            templateTableStatus: [
                { key: '0', label: '待提交' },
                { key: '1', label: '科室待审核' },
                { key: '2', label: '科室已审核' },
                { key: '3', label: '部门待审核' },
                { key: '4', label: '已通过' },
                { key: '5', label: '部门已审核' },
                { key: '6', label: '领导待审核' },
                { key: '7', label: '已通过' },
            ], //文书表格状态
            viewCase: false, //查看案件
            // 登录用户信息
            loginUserInfo: {
                id: '',
                responsibleScope: '', //查询范围
                roleLevel: '', //角色等级
                unitId: '', //内设部门ID
                userRole: '', //角色ID
                permissions: [], // 按钮路径（数据库中的path）
            },
            // 按钮权限
            permissionIsShow: {
                caseAdd: false,
                caseEdit: false,
                caseDelete: false,
                casePass: false,
                caseReject: false,
                documentAdd: false,
                documentEdit: false,
                documentPass: false,
                documentDelete: false,
            }
        };
    },

    created() {
        const info = JSON.parse(localStorage.getItem("user"));
        this.loginUserInfo = {
            id: Number(info.id),
            responsibleScope: info.responsibleScope, //查询范围
            roleLevel: Number(info.roleLevel),
            unitId: Number(info.unitId),
            userRole: Number(info.userRole),
        }
        if (this.caseLog.permissionIsShow) {
            // 将this.caseLog.permissionIsShow所有的值按key赋值给this.permissionIsShow中
            Object.keys(this.caseLog.permissionIsShow).forEach(key => {
                this.permissionIsShow[key] = this.caseLog.permissionIsShow[key];
            });
        }
        this.load();
    },

    methods: {
        // 初始化加载数据
        load() {
            this.getInformSource(); // 加载信息来源
            this.getCaseType(); // 加载案件分类
            this.getUnit();
            this.getUserData(); //加载承办人数据
            this.getCaseTableData(); //加载案件数据
        },
        // 转换案件状态文本
        convertProcess(process) {
            const status = this.caseTableStatus.find(item => item.key === process) || { label: '未知状态', flag: true };
            return {
                label: status.label,
                flag: status.flag,
            };
        },

        // 获取信息来源数据
        getInformSource() {
            request.get("/inform-source/getSource").then(res => {
                if (res.code != '200') {
                    return;
                }
                this.addSelectData.informSourceData = res.data;
            })
        },
        // 获取案件分类数据
        getCaseType() {
            request.get("/case-type/all").then(res => {
                if (res.code != '200') {
                    return;
                }
                this.addSelectData.caseTypeData = res.data;
            })
        },
        // 获取部门数据
        getUnit() {
            if (this.loginUserInfo.unitId !== 1) {
                return
            } else {
                const responsibleScope = this.loginUserInfo.responsibleScope
                if (responsibleScope === '5') {
                    // 所有部门
                    request.get("/unit/filterAfterAllUnit").then(res => {
                        if (res.code === "200") {
                            this.addSelectData.unitData = res.data;
                        }
                    })
                } else if (responsibleScope === '4') {
                    // 部分部门
                    request.get("/unit/filterAfterAllUnit", {
                        params: {
                            userId: this.loginUserInfo.id,
                        }
                    }).then(res => {
                        if (res.code === "200") {
                            this.addSelectData.unitData = res.data;
                        }
                    })
                } else {
                    this.addSelectData.unitData = []
                }
            }
        },
        // 获取用户信息
        getUserData() {
            const responsibleScope = this.loginUserInfo.responsibleScope

            if (responsibleScope === '5') {
                // 所有部门的所有数据
                request.get(`/user/all`).then(res => {
                    if (res.code === '200') {
                        // 过滤出管理员
                        this.addSelectData.userData = res.data.filter(item => item.userRole !== 1);
                    }
                })
            } else if (responsibleScope === '4') {
                // 负责部门的所有数据
                request.get(`/user/responsibleFindAllUser`, {
                    params: {
                        userId: this.loginUserInfo.id,
                    }
                }).then(res => {
                    if (res.code === '200') {
                        this.addSelectData.userData = res.data;
                    }
                })
            } else {
                // 所在部门的所有数据
                request.get(`/user/responsibleFindAllUser`, {
                    params: {
                        unitId: this.loginUserInfo.unitId,
                        userId: this.loginUserInfo.id,
                    }
                }).then(res => {
                    if (res.code === '200') {
                        this.addSelectData.userData = res.data;
                    }
                })
            }
        },
        // 处理案件分页
        handleCaseSizeChange(val) {
            this.casePage.pageSize = val;
            this.getCaseTableData();
        }, //案件表格
        handleCaseCurrentChange(val) {
            this.casePage.currentPage = val;
            this.getCaseTableData();
        },
        // 处理文书分页
        handleTemplateSizeChange(val) {
            this.templateTablePage.pageSize = val;
            this.getTemplateTableData();
        }, //案件文书表格
        handleTemplateCurrentChange(val) {
            this.templateTablePage.currentPage = val;
            this.getTemplateTableData();
        },
        //新建或编辑案件
        clickAddCase: function () {
            if (this.loginUserInfo.unitId !== 1) {
                this.caseForm.unitId = this.loginUserInfo.unitId;
            }
            this.caseTitleType = "新增";
            this.changeCase = true;
        }, //新建案件
        clickEditCase: function (rowData) {
            request.get("/related-file/case?caseno=" + rowData.firstCaseId).then(res => {
                if (res.code != '200') {
                    return;
                }
                let temp = [];
                for (let i = 0; i < res.data.length; ++i) {
                    temp.push({ id: res.data[i]['id'], name: res.data[i]['fileName'], url: res.data[i]['filePath'] })
                }
                this.caseForm = rowData; //先给caseForm
                this.caseForm.annex = temp; //再在caseForm中创建annex
                this.caseTitleType = "编辑";
                this.changeCase = true;
            })
        }, //编辑案件
        async clickChangeCaseSure(formName) {
            this.$refs[formName].validate((valid) => {
                if (!valid) {
                    this.$message.error('请调整数据后再提交')
                    return;
                } else {
                    // 添加录单人
                    this.caseForm.transactor = this.loginUserInfo.id;
                    request.post("/case/edit", this.caseForm).then(async res => {
                        if (res.code == "500") {
                            this.$message.error(res.msg)
                            return;
                        }
                        if (res.code != '200') {
                            return;
                        }
                        this.$message.success('操作成功')
                        this.row = {};
                        this.quxiao();
                        await this.getCaseTableData();

                        this.templateTableData = [];
                        this.templateTablePage.currentPage = 1;
                        this.templateTablePage.total = 0;
                        this.templateData = {
                            documentName: "", // 文书名称
                            pstageId: "",
                            documentType: "",
                            templateNo: "", // 文书模板编号
                            addTemplateNo: "", // 新增时选择的文书
                            addDocumentName: "",
                        };
                        this.NowDocument = [];
                    })
                }
            })
        }, //修改案件确定按钮
        quxiao() {
            this.$refs.caseForm.resetFields();
            this.caseForm = { annex: [] };
            this.changeCase = false;
        },

        //分页请求案件表格数据
        async getCaseTableData() {
            const responsibleScope = this.loginUserInfo.responsibleScope
            if (responsibleScope === '5') {
                // 查询所有案件
                await request.get("/case/findCaseManageUnit", {
                    params: {
                        pageNum: this.casePage.currentPage,
                        pageSize: this.casePage.pageSize,
                        search: this.casePage.search,
                        process: this.caseLog.id,
                    }
                }).then(res => {
                    if (res.code == '200') {
                        this.caseTableData = res.data.records;
                        this.casePage.total = res.data.total;
                    }
                })
            } else if (responsibleScope === '4') {
                // 查询自己负责单位的案件
                await request.get("/case/findCaseManageUnit", {
                    params: {
                        pageNum: this.casePage.currentPage,
                        pageSize: this.casePage.pageSize,
                        search: this.casePage.search,
                        process: this.caseLog.id,
                        userId: this.loginUserInfo.id,
                    }
                }).then(res => {
                    if (res.code == '200') {
                        this.caseTableData = res.data.records;
                        this.casePage.total = res.data.total;
                    }
                })
            } else if (responsibleScope === '3') {
                // 查询自己部门的所有案件
                await request.get("/case/findCaseManageUnit", {
                    params: {
                        pageNum: this.casePage.currentPage,
                        pageSize: this.casePage.pageSize,
                        search: this.casePage.search,
                        process: this.caseLog.id,
                        unitId: this.loginUserInfo.unitId,
                    }
                }).then(res => {
                    if (res.code == '200') {
                        this.caseTableData = res.data.records;
                        this.casePage.total = res.data.total;
                    }
                })
            } else if (responsibleScope === '2') {
                // 指向科室的案件
                await request.get("/case/findCasePageResponsibilityDepartment", {
                    params: {
                        pageNum: this.casePage.currentPage,
                        pageSize: this.casePage.pageSize,
                        search: this.casePage.search,
                        process: this.caseLog.id,
                        userId: this.loginUserInfo.id,
                    }
                }).then(res => {
                    if (res.code == '200') {
                        this.caseTableData = res.data.records;
                        this.casePage.total = res.data.total;
                    }
                })
            } else if (responsibleScope === '1' || responsibleScope === '0') {
                // 指向自己的案件
                await request.get("/case/findCasePointToUser", {
                    params: {
                        pageNum: this.casePage.currentPage,
                        pageSize: this.casePage.pageSize,
                        search: this.casePage.search,
                        process: this.caseLog.id,
                        userId: this.loginUserInfo.id,
                    }
                }).then(res => {
                    if (res.code == '200') {
                        this.caseTableData = res.data.records;
                        this.casePage.total = res.data.total;
                    }
                })
            } else {
                // 没有权限
                this.$message.error('您没有权限查询案件')
                this.caseTableData = [];
                this.casePage.total = 0;
            }

            await this.restoreSelectedRow();
        },
        //删除案件
        clickDeleteCase: function (id) {
            //调用接口删除数据
            this.$confirm('是否确定删除案件?', '提示', {
                showClose: false,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/case/delete/" + id).then(res => {
                    if (res.code != '200') {
                        return;
                    }
                    if (res.data.toString() != "true") {
                        return this.$message.error('删除失败');
                    }
                    this.row = {};
                    this.templateTableData = [];
                    this.templateTablePage.currentPage = 1;
                    this.templateTablePage.total = 0;
                    this.templateData = {
                        documentName: "", // 文书名称
                        pstageId: "",
                        documentType: "",
                        templateNo: "", // 文书模板编号
                        addTemplateNo: "", // 新增时选择的文书
                        addDocumentName: "",
                    };
                    this.NowDocument = [];
                    this.getCaseTableData();
                    this.$message.success('删除成功');
                })
            }).catch(() => {
            });
        },

        // 恢复选中状态
        async restoreSelectedRow() {
            // 保存当前选中状态
            const selectedId = this.row.id;

            // 恢复选中状态
            if (selectedId) {
                this.$nextTick(() => {
                    const index = this.caseTableData.findIndex(item => item.id === selectedId);
                    if (index !== -1) {
                        this.$refs.table1.setCurrentRow(this.caseTableData[index]);
                        this.selectCaseRow(this.caseTableData[index]);
                    }
                });

            }
        },

        //分页请求案件文书表格数据
        async getTemplateTableData() {
            await request.get("/params/page", {
                params: {
                    caseId: this.row.firstCaseId,
                    pageNum: this.templateTablePage.currentPage,
                    pageSize: this.templateTablePage.pageSize,
                }
            }).then(res => {
                if (res.code != '200') {
                    return;
                }
                for (let key in res.data) {
                    if (key == "records") {
                        this.templateTableData = res.data[key];
                    }
                    if (key == "total") {
                        this.templateTablePage.total = res.data[key];
                    }
                }
            });
        },

        selectOption(selectedOption) {
            this.casePage.currentPage = 1;
            this.getCaseTableData(); //分页请求案件表格数据
            // 初始化数据
            this.initAllData();
        },

        //案件点击行数据
        selectCaseRow(row) {
            this.row = { ...row }
            // 保存选中行的索引
            this.selectedRowIndex = this.caseTableData.findIndex(item => item.id === row.id);
            this.selectedCaseNo = row.caseNo;
            this.getTemplateTableData();
            this.getNowDocument();
        },

        // 获取当前案件可添加文书
        getNowDocument() {
            request.get("/archive-node/getNowDocument?routineTypeId=" + this.row.routineTypeId + "&archiveNodeId=" + this.row.archiveNodeId).then(res => {
                if (res.code != '200') {
                    return;
                }
                if (res.data != null) {
                    this.NowDocument = [];
                    this.templateData = {
                        documentName: "", // 文书名称
                        pstageId: "",
                        documentType: "",
                        templateNo: "", // 文书模板编号
                        addTemplateNo: "", // 新增时选择的文书
                        addDocumentName: "", // 新增时选择的文书名称
                    };
                    for (let key in res.data) {
                        this.NowDocument.push({ key: key, name: res.data[key] }); //同样循环构造选项数据数组
                    }
                }
            });
        },
        selectAddArchive(item) {
            // 从数组中找到这一行
            this.NowDocument.forEach(element => {
                if (element.key == item) {
                    this.templateData.addTemplateNo = element.key;
                    this.templateData.addDocumentName = element.name;
                }
            });
        },
        // 点击下一步
        clickNextDocumentType() {
            if (!this.row.id) {
                return this.$message.error('请选中案件');
            }

            request.get("/archive-branch-node/findNextNode?", {
                params: {
                    routineTypeId: this.row.routineTypeId,
                    archiveNodeId: this.row.archiveNodeId,
                }
            }).then(res => {
                if (res.code != '200') {
                    return;
                }
                if (res.data == null) {
                    this.$message({
                        type: "warning",
                        message: "已到达最后一步！"
                    });
                } else {
                    if (res.data.length > 1) {
                        this.nextDocumentTypeData = res.data;
                        this.dialogNextDocumentType = true;
                    } else if (res.data.length === 1) {
                        request.get("/archive-node/getNextDocumentType", {
                            params: {
                                id: res.data[0].id,
                                caseId: this.row.id,
                            }
                        }).then(re => {
                            if (re.code == 200) {
                                this.$message({
                                    type: "success",
                                    message: "操作成功"
                                });
                                // 恢复选中状态
                                this.getCaseTableData();
                                if (re.data != null) {
                                    this.NowDocument = [];
                                    // 清空选中状态
                                    this.templateData = {
                                        documentName: "", // 文书名称
                                        pstageId: "",
                                        documentType: "",
                                        templateNo: "", // 文书模板编号
                                        addTemplateNo: "", // 新增时选择的文书
                                        addDocumentName: "", // 新增时选择的文书名称
                                    };
                                    for (let key in re.data) {
                                        this.NowDocument.push({ key: key, name: re.data[key] });
                                    }
                                }
                            } else {
                                this.$message({
                                    type: "warning",
                                    message: "操作错误"
                                });
                            }
                        });
                    }
                }
            });
        },

        clickLastDocumentType() {
            if (!this.row.id) {
                return this.$message.error('请选中案件');
            }
            if (this.row.id == "") {
                return this.$message.error('请选择需要增加文书的案件');
            }

            request.get("/archive-branch-node/findLastNode", {
                params: {
                    caseId: this.row.firstCaseId,
                }
            }).then(res => {
                if (res.code == 200) {
                    // 恢复选中状态
                    this.getCaseTableData();
                    if (res.data != null) {
                        this.$message({
                            type: "success",
                            message: "操作成功"
                        });
                        this.NowDocument = [];
                        // 清空选中状态
                        this.templateData = {
                            documentName: "", // 文书名称
                            pstageId: "",
                            documentType: "",
                            templateNo: "", // 文书模板编号
                            addTemplateNo: "", // 新增时选择的文书
                            addDocumentName: "", // 新增时选择的文书名称
                        };
                        for (let key in res.data) {
                            this.NowDocument.push({ key: key, name: res.data[key] });
                        }
                    } else {
                        this.$message({
                            type: "warning",
                            message: "已到达第一步"
                        });
                    }
                } else {
                    this.$message({
                        type: "warning",
                        message: "操作错误"
                    });
                }
            });
        },
        // 弹窗点击下一步
        clickNextDocumentTypeEnsure(row) {
            request.get("/archive-node/getNextDocumentType", {
                params: {
                    id: row.id,
                    caseId: this.row.id,
                }
            }).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: "success",
                        message: "操作成功"
                    })
                    this.getCaseTableData()
                    if (res.data != null) {
                        this.NowDocument = [];
                        // 清空选中状态
                        this.templateData = {
                            documentName: "", // 文书名称
                            pstageId: "",
                            documentType: "",
                            templateNo: "", // 文书模板编号
                            addTemplateNo: "", // 新增时选择的文书
                            addDocumentName: "", // 新增时选择的文书名称
                        };
                        for (let key in res.data) {
                            this.NowDocument.push({ key: key, name: res.data[key] });
                        }
                    }
                } else {
                    this.$message({
                        type: "warning",
                        message: "操作错误"
                    })
                }
            })
            this.dialogNextDocumentType = false;
        },

        // 双击点击文书
        DoubleHandleDocumentsRowClick(row, event, column) {
            if (this.permissionIsShow.documentEdit && row.status != '4') {
                this.editAndViewDocuments('编辑', row)
            } else {
                this.editAndViewDocuments('查看', row)
            }
        },
        editAndViewDocuments(type, scope) {
            if (type === '编辑') {
                this.templateData.isEdit = '编辑';
            } else if (type === '查看') {
                this.templateData.isEdit = '查看';
            }
            this.templateData.templateNo = scope.templateNo;
            this.templateData.documentName = scope.name;
            this.clickAddDocument(scope.id, scope.documentName);
        },

        //删除文书
        clickDeleteTemplate: function (id) {
            this.$confirm('是否确定删除文书?', '提示', {
                showClose: false,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/params/delete/" + id).then(res => {
                    if (res.code != '200') {
                        return;
                    }
                    if (res.data.toString() == "true") {
                        this.$message.success('删除成功');
                        this.getTemplateTableData();
                    } else {
                        this.$message.error('删除失败');
                    }
                })
            }).catch(() => {
            });
        },

        //增加文书或编辑文书或查看文书
        clickAddDocument: function (id, documentName) {
            window.getTemplateData = (callback) => {
                this.getTemplateData(id, callback);
            }
            window.postTemplateDate = (data, formData) => {
                this.postTemplateDate(id, data, formData);
            }
            window.changeTemplateDow = () => {
                this.changeTemplateDow();
            }
            if (documentName) {
                this.templateData.documentName = documentName;
                document.title = documentName;
                this.clickTemplate = true;
                return;
            } //通过是否有文书名传入判断是新增还是编辑
            if (!this.row.id) {
                return this.$message.error('请选中案件');
            } //校验是否选中案件
            if (!this.templateData.addTemplateNo) {
                return this.$message.error('请选择具体文书');
            } //校验是否选取文书

            // 重新将下拉框的值给到文书渲染
            this.templateData.templateNo = this.templateData.addTemplateNo;
            this.templateData.documentName = this.templateData.addDocumentName;
            request.get("/params/getDoc?caseId=" + this.row.firstCaseId
                + "&templateNo=" + this.templateData.templateNo).then(res => {
                    if (res.code != '200') {
                        return;
                    }
                    // if (res.data != null) {
                    //   return this.$message.error('该文书已存在');
                    // } //判断文书是否存在
                    document.title = this.templateData.documentName;
                    this.clickTemplate = true;
                })
        }, //增加或编辑或查看文书按钮

        getTemplateData: function (id, callback) {
            request.post("/params/paramContent", {
                id: id,
                caseId: this.row.firstCaseId,
                templateNo: this.templateData.templateNo
            }).then(res => {
                if (res.code != '200') {
                    return;
                }
                if (res.data != null) {
                    callback(JSON.parse(res.data.paramContent), res.data.status);
                }
            })
        }, //获取文书数据

        postTemplateDate: function (id, data, formData) {
            this.$confirm('是否确定提交文书?', '提示', {
                showClose: false,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                return request.post("/params/edit", {
                    id: id,
                    caseId: this.row.firstCaseId,
                    templateNo: this.templateData.templateNo,
                    paramContent: JSON.stringify(data)
                });
            })
                .then(res => {
                    if (res.code != '200') {
                        this.$message.error('提交失败');
                        return Promise.reject('提交失败');
                    }

                    this.$message.success('提交成功');

                    // 如果有formData，则保存PDF
                    if (formData) {
                        return axios.post("/api/related-file/uploadPDF", formData, {
                            params: {
                                id: res.data.id
                            },
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        });
                    }
                })
                .then(() => {
                    this.closeTemplate();
                    this.getTemplateTableData();
                    this.getNowDocument();
                })
                .catch(error => {
                    if (error !== '提交失败') {
                        this.$message.error('操作失败');
                    }
                });
        }, //修改文书数据

        closeTemplate: function () {
            this.getNowDocument();
            this.clickTemplate = false;
            document.title = "案件管理";
        }, //关闭文书渲染页面

        // 查看文书页面禁止编辑
        changeTemplateDow() {
            if (this.templateData.isEdit == '查看') {
                this.$refs.iframe.contentDocument.getElementById('pdfDom').style.pointerEvents = 'none';
            }
        },


        //相关附件
        clickRelatedAnnex: function () {
            if (!this.row.id) {
                return this.$message.error('请选中案件');
            }
            this.relatedAnnex = true;
            request.get("/related-file/case?caseno=" + this.row.firstCaseId + "&keyWord=" + this.searchFileName).then(res => {
                if (res.code != '200') {
                    return;
                }
                this.annexTable = res.data;
            })
        },
        // 关闭相关附件弹窗
        relatedAnnexClose() {
            this.relatedAnnex = false;
            this.annexTable = [];
            this.searchFileName = '';
        },
        // 编辑相关附件
        editRelatedAnnex(item) {
            Object.assign(this.annexForm, item)
            this.dialogRelatedAnnex = true
        },
        // 新增相关附件
        addRelatedAnnex() {
            this.dialogRelatedAnnex = true;
        },
        // 新增/编辑弹窗上传附件
        relatedAnnexUploadSuccess(res) {
            if (res.code != '200') {
                return;
            }
            this.annexForm.filePath = res.data.url
            if (this.annexForm.fileName === null || this.annexForm.fileName === '') {
                this.annexForm.fileName = res.data.name
            }
        },
        // 新增/编辑弹窗删除附件
        deleteRelatedAnnex() {
            this.annexForm.filePath = '';
            this.$message.success('删除成功');
        },
        // 提交相关附件
        submitRelatedAnnex() {
            this.annexForm.firstCaseId = this.row.firstCaseId;
            this.annexForm.uploadUnitId = this.loginUserInfo.unitId;
            this.annexForm.uploadUserId = this.loginUserInfo.id;
            request.post("/related-file/edit", this.annexForm).then(res => {
                if (res.code != '200') {
                    return;
                }
                this.closeRelatedAnnex();
                this.clickRelatedAnnex();
                this.$message.success("上传成功");
            })
        },
        // 取消相关附件编辑弹窗
        closeRelatedAnnex() {
            this.dialogRelatedAnnex = false;
            this.annexForm = {};
        },
        // 下载相关附件
        downloadrelatedAnnexFile(row) {
            // 创建一个link下载
            try {
                const link = document.createElement('a');
                link.href = '/api/related-file/download?filePath=' + row.filePath;
                link.download = row.fileName;

                document.body.appendChild(link);

                // 使用requestAnimationFrame确保DOM已更新
                requestAnimationFrame(() => {
                    link.click();

                    setTimeout(() => {
                        document.body.removeChild(link);
                    }, 100);
                });

            } catch (error) {
                console.error('下载错误:', error);
            }
        },
        deleteRelatedAnnexFile(row) {
            if (!row.id) {
                return;
            }
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/related-file/delete/" + row.id).then(res => {
                    if (res.code != '200') {
                        return;
                    }
                    if (res.data.toString() == "true") {
                        this.$message.success('删除成功');
                        this.clickRelatedAnnex();
                    } else {
                        this.$message.error('删除失败');
                    }
                })
            });
        },
        async openFile(fileUrl) {
            this.openItemFileDialog = true
            const fullUrl = this.serverIp + '/file/download/' + fileUrl
            this.fileExt = fileUrl.split('.').pop().toLowerCase()
            console.log(fullUrl)
            try {
                if (this.fileExt !== "docx" && this.fileExt !== "doc") {
                    this.pdfSrc = fullUrl
                } else {
                    const previewUrl = `/api/related-file/preview/${encodeURIComponent(fileUrl.split('/').pop())}`
                    const response = await fetch(previewUrl)
                    const blob = await response.blob()
                    this.pdfSrc = URL.createObjectURL(blob)
                }
            } catch (error) {
                this.$message.error('文档预览失败: ' + error.message)
            }
        },
        // 上传前校验文件大小
        beforeAnnexUpload(file) {
            const maxSize = 1024 * 1024 * 1024;
            const fileSize = file.size;

            if (fileSize > maxSize) {
                // 文件太大，拦截
                this.$message.error('文件大小不能超过100MB');
                return false;
            }
            return true;
        },
        // 附件上传成功函数
        annexUploadSuccess: function (res) {
            if (res.code != '200') {
                return;
            }
            this.caseForm.annex.push(res.data);
            this.$message.success('上传成功');
        },
        // 附件删除函数
        annexRemove: function (uploadFile) {
            if (!uploadFile.id) {
                return;
            }
            request.get("/related-file/delete/" + uploadFile.id).then(res => {
                if (res.code != '200') {
                    return;
                }
                if (res.data.toString() == "true") {
                    this.caseForm.annex = this.caseForm.annex.filter((file) => file.id !== uploadFile.id);
                    this.$message.success('删除成功');
                } else {
                    this.$message.error('删除失败');
                }
            })
        },
        //通过文书
        clickApprovedTemplate(id) {
            let status = (this.row.routineTypeId === 1 && this.caseLog.id === '5') ? '7' : this.caseLog.passTemplateStatus;
            request.get("/params/changeStatus", {
                params: {
                    id: id,
                    status: status
                }
            }).then(res => {
                if (res.code != '200') {
                    return;
                }
                this.getTemplateTableData();
                this.$message.success("通过文书");
            })
        },


        // 提交案件按钮点击事件
        async clickSubmitReview() {
            if (!this.row.id) {
                return this.$message.error('请选中案件');
            }

            if (!this.caseLog.templateStatus) {
                return this.$message.error('系统异常，请重新登录');
            }
            // 查找本案是否有未通过的文书
            const templateStatus = this.caseLog.templateStatus;
            let statusRes = await request.get("/case/submitBeforeJudgmentStatus", {
                params: {
                    caseId: this.row.firstCaseId,
                    status: templateStatus.join(',')
                }
            })

            if (statusRes.code === '200') {
                if (statusRes.data) {
                    return this.$message.warning(`本案还有未通过的文书，请检查通过后再次提交。`);
                } else {
                    if (this.caseLog.id == '5' && this.row.routineTypeId == 1) {
                        this.caseClickApprovePass();
                        return
                    }
                    if (this.caseLog.submitTitle.length > 1) {
                        this.multiDirectional = this.caseLog.submitTitle.map((item, index) => ({
                            label: item,
                            value: index
                        }));
                        // 多提交方向
                        this.submitMultiDirectional = true;
                    } else {
                        // 一个提交方向
                        this.submitIndex = 0;
                        this.isShowSubmitDepartmentSelect = this.showSubmitDepartmentSelect();
                        this.isShowSubmitUserSelect = this.showSubmitUserSelect();
                        // 需要获取部门数据
                        if (this.caseLog.id === '0' || this.caseLog.id === '1') {
                            await this.getDepartmentData(this.row.unitId);
                        }
                        this.submit = true;
                    }
                }
            } else {
                return this.$message.error('系统出现问题，请联系管理员');
            }
        },
        // 获取部门信息
        async getDepartmentData(unitId) {
            // 获取科室信息
            let deptRes = await request.get('/department/unitDepartment', {
                params: {
                    unitId: unitId,
                    isRoot: 0,
                }
            })
            if (deptRes.code === '200') {
                // 转换为树状结构
                this.submitSelectOptions.departmentOption = this.convertToTree(deptRes.data);
            } else {
                return this.$message.error('系统出现问题，请联系管理员');
            }
        },
        // 获取单位下的用户
        async getUnitUsers(unitId) {
            request.get('/user/findUserDataByUnitId', {
                params: {
                    unitId: unitId,
                }
            }).then(res => {
                if (res.code != '200') {
                    return;
                }
                this.submitForm.userId = '';
                this.submitSelectOptions.userOption = res.data.filter(item => item.userRole !== 1);
            })
        },
        // 获取科室下的所有用户
        async getDepartmentUsers(departmentId) {
            request.get('/user/findUserDataByDepartmentId', {
                params: {
                    departmentId: departmentId,
                }
            }).then(res => {
                if (res.code != '200') {
                    return;
                }
                this.submitForm.userId = '';
                this.submitSelectOptions.userOption = res.data;
            })
        },
        // 将扁平数据转换为树状结构的函数
        convertToTree(flatData) {
            // 创建ID到节点的映射，便于快速查找
            const idToNode = {};
            const tree = [];

            // 构建节点映射表
            flatData.forEach(node => {
                // 复制节点数据，避免修改原始数据
                idToNode[node.id] = { ...node, children: [] };
            });

            // 构建树状结构
            flatData.forEach(node => {
                const currentNode = idToNode[node.id];
                const parentId = node.pid;

                // 如果是顶级节点（pid为null），直接添加到树中
                if (parentId === null) {
                    tree.push(currentNode);
                } else {
                    // 否则，将当前节点添加到父节点的children数组中
                    const parentNode = idToNode[parentId];
                    if (parentNode) {
                        parentNode.children.push(currentNode);
                    }
                }
            });

            return tree;
        },
        // 选择科室处理
        submitFormHandleDepartmentChange(path) {
            if (path.length > 0) {
                // 级联选择器的最后一个节点即为所选科室
                const selectedDepartment = path[path.length - 1];
                this.submitForm.departmentId = selectedDepartment;
                // 获取科室下的用户
                this.getDepartmentUsers(selectedDepartment);
            } else {
                this.submitForm.departmentId = '';
            }
        },
        // 多提交方向弹窗点击行处理
        async handleMultiDirectionalRowClick(row) {
            this.submitIndex = row.value;
            this.isShowSubmitDepartmentSelect = this.showSubmitDepartmentSelect();
            this.isShowSubmitUserSelect = this.showSubmitUserSelect();

            this.submitMultiDirectional = false;
            this.submit = true;
            if (this.caseLog.id === '0' || this.caseLog.id === '1') {
                // 需要获取部门数据
                await this.getDepartmentData(this.row.unitId);
            } else if (this.caseLog.id === '5' && this.submitIndex === 0) {
                // 获取管委会的用户数据
                await this.getUnitUsers(1);
            }
        },
        // 是否显示科室选择器
        showSubmitDepartmentSelect() {
            let isShow = false;
            const id = this.caseLog.id;
            const index = this.submitIndex;
            if (id === '0') {
                isShow = true;
            } else if (id === '1' && index === 0) {
                isShow = true;
            }
            return isShow;
        },
        // 是否显示用户选择器
        showSubmitUserSelect() {
            let isShow = false;
            const id = this.caseLog.id;
            const index = this.submitIndex;
            if (id === '0') {
                isShow = true;
            } else if (id === '1' && index === 0) {
                isShow = true;
            } else if (id === '5' && index === 0) {
                isShow = true;
            }
            return isShow;
        },

        // 确定提交按钮
        clickSubmitReviewSure() {
            this.$refs.submitForm.validate((valid) => {
                if (!valid) {
                    this.$message.error('请调整数据后再提交')
                    return;
                }
                const formData = {
                    // 案件ID
                    id: this.row.id,
                    // 谁提交的
                    loginUserId: this.loginUserInfo.id,
                    // 提交给谁
                    userId: this.submitForm.userId,
                    // 说明备注
                    explain: this.submitForm.explain,
                    // 应该修改的状态码
                    process: this.caseLog.submitProcess[this.submitIndex],
                }

                request.post("/case/submitCheck", formData).then(res => {
                    if (res.code != '200') {
                        return;
                    }
                    if (res.data.toString() != "true") {
                        return this.$message.error('审核失败');
                    }
                    // 刷新页面
                    this.initAllData();
                    this.$message.success('审核成功');
                })
            })
        },
        // 审批通过按钮
        async caseClickApprovePass() {
            if (!this.row.id) {
                return this.$message.error('请选中案件');
            }

            if (!this.caseLog.templateStatus) {
                return this.$message.error('系统异常，请重新登录');
            }
            // 查找本案是否有未通过的文书
            const templateStatus = this.caseLog.templateStatus;
            let statusRes = await request.get("/case/submitBeforeJudgmentStatus", {
                params: {
                    caseId: this.row.id,
                    status: templateStatus.join(',')
                }
            })

            if (statusRes.code === '200') {
                if (statusRes.data) {
                    return this.$message.warning(`本案还有未通过的文书，请检查通过后再次提交。`);
                } else {
                    const formData = {
                        // 案件ID
                        id: this.row.id,
                        // 谁提交的
                        loginUserId: this.loginUserInfo.id,
                    }
                    request.post("/case/caseApprovePass", formData).then(res => {
                        if (res.code != '200') {
                            return this.$message.error('审批通过失败');
                        }
                        if (res.data.toString() != "true") {
                            return this.$message.error('审批通过失败');
                        }
                        // 刷新页面
                        this.initAllData();
                        this.$message.success('审批通过成功');
                    })
                }
            }
        },
        // 取消提交按钮
        clickCancelSubmitReview() {
            this.$refs.submitForm.resetFields();
            this.submit = false;
        },

        // 所有数据初始化
        initAllData() {
            this.row = {};
            this.selectedRowIndex = -1
            this.selectedCaseNo = ''

            //查看文书数据
            this.templateData = {
                documentName: "", // 文书名称
                pstageId: "",
                documentType: "",
                templateNo: "", // 文书模板编号
                addTemplateNo: "", // 新增时选择的文书
                addDocumentName: "", // 新增时选择的文书名称
            }

            // 当前案件可添加文书
            this.NowDocument = []

            this.templateTableData = [] //案件文书表格数据
            this.templateTablePage = {
                currentPage: 1,
                pageSize: 10,
                total: 0,
            }

            // 案件提交初始化
            this.submitIndex = 0;
            if (this.$refs.submitForm) {
                this.$refs.submitForm.resetFields();
            }
            this.submit = false;
            // 提交审核下拉框选项初始化
            this.submitSelectOptions = {
                departmentOption: [], //提交审核科室表单下拉框选项
                userOption: [], //提交审核用户表单下拉框选项
            }

            // 案件驳回初始化
            if (this.$refs.backForm) {
                this.$refs.backForm.resetFields();
            }
            this.back = false;


            this.getCaseTableData();
        },

        // 点击驳回按钮
        clickReject() {
            if (!this.row.id) {
                return this.$message.error('请选中案件');
            }
            // 赋值案件ID
            this.backForm.id = this.row.id;
            this.back = true;
        },
        // 点击驳回确定按钮
        clickBackSure() {
            this.$refs.backForm.validate(valid => {
                if (!valid) {
                    return this.$message.error('请填写驳回说明');
                }
                request.get("/case/caseBack", {
                    params: {
                        id: this.backForm.id,
                        backReason: this.backForm.backReason,
                        process: this.caseLog.backProcess,
                    }
                }).then(res => {
                    if (res.code != '200') {
                        return this.$message.error('驳回失败');
                    }
                    if (res.data.toString() != "true") {
                        return this.$message.error('驳回失败');
                    }
                    // 刷新页面
                    this.initAllData();
                    this.$message.success('驳回成功');
                })
            })
        },
        // 点击驳回取消按钮
        clickCancelBack() {
            this.$refs.backForm.resetFields();
            this.back = false;
        },
        // 是否办理返回字符串
        caseIsHanding(isHanding) {
            if (isHanding === '0') {
                return '未办理'
            } else if (isHanding === '1') {
                return '办理中'
            } else if (isHanding === '2') {
                return '已完结'
            } else {
                return '-'
            }
        },
        //查看案件
        clickViewCase(rowData) {
            // 保存当前行数据用于标题显示
            const currentRow = { ...rowData };

            // 构造案件信息表格数据
            const viewCaseTable = [
                { title: '所属单位', data: currentRow.unitName || '-' },
                { title: '案件编号', data: currentRow.caseNo || '-' },
                { title: '案件名称', data: currentRow.caseName || '-' },
                { title: '案件状态', data: this.convertProcess(currentRow.process).label || '-' },
                { title: '案件程序', data: currentRow.routineType || '-' },
                { title: '来源', data: currentRow.informName || '-' },
                { title: '案件分类', data: currentRow.typeName || '-' },
                { title: '违法类型', data: currentRow.illegalType || '-' },
                { title: '案件说明', data: currentRow.explains || '-' },
                { title: '备注', data: currentRow.remark || '-' },
                { title: '录入时间', data: currentRow.enterTime || '-' },
                { title: '办理情况', data: this.caseIsHanding(currentRow.isHanding) || '-' },
                { title: '录单人', data: currentRow.transactorName || '-' },
                { title: '承办人一', data: currentRow.undertakerOneName || '-' },
                { title: '承办人二', data: currentRow.undertakerTwoName || '-' },
                ...(this.isShowViewCaseData("录单人提交说明", currentRow) ? [{ title: '录单人提交说明', data: currentRow.transactorExplain || '-' }] : []),
                ...(this.isShowViewCaseData("科室审核人", currentRow) ? [{ title: '科室审核人', data: currentRow.squadronLeaderName || '-' }] : []),
                ...(this.isShowViewCaseData("科室审核说明", currentRow) ? [{ title: '科室审核说明', data: currentRow.squadronLeaderExplain || '-' }] : []),
                ...(this.isShowViewCaseData("法律审核人（部门法规科）", currentRow) ? [{ title: '法律审核人（部门法规科）', data: currentRow.lawDepartmentName || '-' }] : []),
                ...(this.isShowViewCaseData("法律审核说明（部门法规科）", currentRow) ? [{ title: '法律审核说明（部门法规科）', data: currentRow.lawDepartmentExplain || '-' }] : []),
                ...(this.isShowViewCaseData("部门审核人", currentRow) ? [{ title: '部门审核人', data: currentRow.directorName || '-' }] : []),
                ...(this.isShowViewCaseData("部门审核说明", currentRow) ? [{ title: '部门审核说明', data: currentRow.directorExplain || '-' }] : []),
                ...(this.isShowViewCaseData("法律审核人（法律服务中心）", currentRow) ? [{ title: '法律审核人（法律服务中心）', data: currentRow.serviceName || '-' }] : []),
                ...(this.isShowViewCaseData("法律审核说明（法律服务中心）", currentRow) ? [{ title: '法律审核说明（法律服务中心）', data: currentRow.serviceExplain || '-' }] : []),
                ...(this.isShowViewCaseData("审批领导", currentRow) ? [{ title: '审批领导', data: currentRow.leaderName || '-' }] : []),
                ...(this.isShowViewCaseData("驳回原因", currentRow) ? [{ title: '驳回原因', data: currentRow.backReason || '-' }] : []),
            ];

            this.viewCaseTable = viewCaseTable;
            this.viewCase = true;
        },
        // 查看数据是否显示
        isShowViewCaseData(type, data) {
            const process = data.process;
            const log = this.caseLog.id;
            if (type == '录单人提交说明') {
                return log !== '0'
            } else if (type == '科室审核人') {
                return log !== '0' && log !== '1'
            } else if (type == '科室审核说明') {
                return log !== '0' && log !== '1' && log !== '2'
            } else if (type == '法律审核人（部门法规科）') {
                return log !== '0' && log !== '1' && log !== '2' && log !== '3'
            } else if (type == '法律审核说明（部门法规科）') {
                return log !== '0' && log !== '1' && log !== '2' && log !== '3' && log !== '4'
            } else if (type == '部门审核人') {
                return log !== '0' && log !== '1' && log !== '2' && log !== '3' && log !== '4' && log !== '5'
            } else if (type == '部门审核说明') {
                return log === '7' || log === '8' || log === '9' || log === '10' || log === '11'
            } else if (type == '法律审核人（法律服务中心）') {
                return log === '8' || log === '9' || log === '10' || log === '11'
            } else if (type == '法律审核说明（法律服务中心）') {
                return log === '9' || log === '10' || log === '11'
            } else if (type == '审批领导') {
                return log === '10' || log === '11'
            } else if (type == '驳回原因') {
                return process === '2' || process === '4' || process === '6' || process === '8' || process === '10'
            } else {
                return false;
            }
        },
        // 单独下载一个文书的PDF
        clickDownloadTemplate: function (row, caseNo) {
            if (row && row.pdf) {
                try {
                    const link = document.createElement('a');
                    link.href = row.pdf;
                    link.download = `${caseNo || row.caseNo}-${row.documentName || '文书'}.pdf`;

                    document.body.appendChild(link);

                    // 使用requestAnimationFrame确保DOM已更新
                    requestAnimationFrame(() => {
                        link.click();

                        setTimeout(() => {
                            document.body.removeChild(link);
                        }, 100);
                    });

                } catch (error) {
                    console.error('下载错误:', error);
                }
            }
        },

        // 根据案件批量下载文书的PDF
        clickBatchDownload: function (row) {
            // 显示加载状态
            const loading = this.$loading({
                lock: true,
                text: '正在准备下载文书...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            request.get("/params/getPdfList", {
                params: {
                    caseId: row.firstCaseId
                }
            }).then(res => {
                // 关闭加载状态
                loading.close();

                if (res.code === '200') {
                    const pdfList = res.data || [];

                    if (pdfList.length === 0) {
                        this.$message.warning('未找到可下载的文书');
                        return;
                    }

                    this.$message({
                        message: `共${pdfList.length}个文书，正在下载，请不要离开本页面。`,
                        type: 'info',
                        duration: 3000
                    });
                    this.isDownloading = true;
                    // 将连续下载进度统一成一个进度
                    this.totalFiles += pdfList.length;

                    // 逐个下载，添加延迟避免浏览器拦截
                    pdfList.forEach((item, index) => {
                        setTimeout(() => {
                            this.clickDownloadTemplate(item, row.caseNo);

                            this.downloadedFiles++;
                            this.percentage = Math.round(this.downloadedFiles / this.totalFiles * 100);

                            // 下载完成后关闭进度条
                            if (this.percentage === 100) {
                                // 只有下载完成，才会重置进度，避免切换页面导致进度条混乱
                                this.isDownloading = false;
                                this.totalFiles = 0;
                                this.downloadedFiles = 0;
                            }

                        }, index * 800); // 每个文件间隔1秒下载
                    });

                } else {
                    this.$message.error('获取文书失败');
                }
            }).catch(error => {
                // 关闭加载状态
                loading.close();
                // 关闭弹窗
                this.isDownloading = false;
                this.$message.error('请求失败，请稍后重试');
                console.error('批量下载请求错误:', error);
            });
        },

    }, //methods
}
</script>

<style scoped>
:deep(.el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell) {
    background-color: #57bfff8e !important;
}

.download-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.381);
    z-index: 999;
}

.download-progress-container {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    text-align: center;
}

.download-close-btn {
    position: relative;
    background: transparent;
    border: none;
    font-size: 16px;
    color: #909399;
    cursor: pointer;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.download-close-btn:hover {
    background-color: #f5f5f5;
    color: #606266;
}

/*   外框架   */
.frameworkOut {
    height: calc(100vh - 88px);
    width: calc(100vh - 200px);
    margin-left: 8px;
    border: solid 1px #D3D3D3;
}

/*   文书内框架   */
.frameworkIn1 {
    height: calc(100vh - 92px);
    width: 100%;
    border: solid 1px #D3D3D3;
}

/*   案件管理内框架   */
.frameworkIn2 {
    height: calc(100vh - 92px);
    width: 100%;
    border: solid 1px #D3D3D3;
}

/*   文书标题   */
.templateHeader {
    font-size: 19px;
    font-weight: bold;
    padding: 4px 20px;
    height: 30px;
    border: 1px solid #CCCCCC;
    background-color: #E0ECFF;
}

/*   文书底边   */
.templateFooter {
    text-align: center;
    margin-top: -4px;
    padding: 4px 20px;
    height: 30px;
    border: 1px solid #CCCCCC;
    background-color: #E0ECFF;
}

/*   表格大标题   */
.header {
    font-size: 16px;
    font-weight: bold;
    padding: 4px 20px;
    height: 22px;
    background-color: #CCCCCC;
    /*备选 #D3D3D3*/
}

/*   表格按键组   */
.button_group {
    padding: 4px 20px;
    background-color: #DDDDDD;
}

/*   表格底边   */
.footer {
    padding: 4px 10px;
    height: 32px;
    background-color: #f4f3f9;
}

.templateTableStyle {
    width: 100%;
    height: calc(50vh - 116px);
}

/*   附件弹窗   */
.annexDialog {
    height: 600px;
    border: solid 1px #D3D3D3;
}

/*   阶段弹窗   */


:deep(.el-upload-dragger) {
    border: Dashed 2px #D3D3D3;
}

:deep(.el-upload__text) {
    font-size: 16px !important;
}

::v-deep .el-table__body tr.current-row>td {
    color: #ffffff;
    background: #57bfff !important;
    /*备选#ebeef5  #f4f3f9 #dddddd #ffe48d*/
}
</style>
